<template>
  <div class="like" @click.stop="toggleLike">
    <img class="image" :src="iconSrc" alt="">
    <span class="text">{{favNum}}</span>
  </div>
</template>

<script>
const db = wx.cloud.database()
export default {
  name: 'Like',
  props: {
    favNum: {
      type: Number,
      default: 0
    },
    isLike: {
      type: Boolean,
      default: 0
    },
    currentOne: Object
  },
  computed: {
    iconSrc () {
      return this.isLike ? 'https://7465-test-1082be-1257701543.tcb.qcloud.la/icon/like@2x.png?sign=4365ccd0caed84ae74861bdf0cba0db8&t=1538310409' : 'https://7465-test-1082be-1257701543.tcb.qcloud.la/icon/unlike@2x.png?sign=db5f90b5d18f2ad98e41ad763094452b&t=1538310427'
    }
  },
  methods: {
    async toggleLike () {
      this.isLike = !this.isLike
      this.favNum += this.isLike ? 1 : -1
      // this.$emit('toggleLike', [this.isLike, this.favNum])
      wx.cloud.callFunction({
        name: 'uploadLike',
        data: {
          fav_nums: this.favNum,
          _id: this.currentOne._id
        }
      })
      if (this.isLike) {
        this.currentOne.fav_nums = this.favNum
        await db.collection('likes').add({
          data: {
            ...this.currentOne,
            createTime: db.serverDate()
          }
        })
      } else {
        await wx.cloud.callFunction({
          name: 'removeLike',
          data: {
            _id: this.currentOne._id
          }
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  .like
    display inline-block
    vertical-align middle
    .image
      width 32rpx
      height 28rpx
    .text
      padding-left 4rpx
      vertical-align text-top
      font-size 24rpx
      color #bbbbbb
</style>
